package com.spzx.product.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.ProductUnit;
import com.spzx.product.service.ProductUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("unit")

@Tag(name = "商品单位管理模块")
public class ProductUnitController extends BaseController {
    @Resource
    ProductUnitService productUnitService;

    @Operation(summary = "条件查询分页数据")
    @GetMapping("list")
    public TableDataInfo list(ProductUnit productUnit) {

        Page<ProductUnit> page = productUnitService.selectUnitPage(productUnit);
        return new TableDataInfo(page.getRecords(), (int) page.getTotal());
    }



    @Operation(summary = "查询所有")
    @GetMapping
    public AjaxResult listAll(){
        return success(  productUnitService.list());

    }

    @Operation(summary = "批量删除")
    @DeleteMapping("{ids}")
    public AjaxResult remove(@PathVariable("ids") List<Long> ids){
        return toAjax(productUnitService.removeBatchByIds(ids));
    }



    @Operation(summary = "根据id查询详情")
    @GetMapping("{id}")
    public AjaxResult getById(@PathVariable Long id){
        return  success(productUnitService.getById(id)  );

    }




    @Operation(summary = "修改")
    @PutMapping
    public AjaxResult edit(@RequestBody ProductUnit productUnit){
        if (!productUnitService.checkUnitNameUnique(productUnit)){
            return error("更新商品单位'" + productUnit.getName() + "'失败，商品单位名称已存在");
        }
        productUnit.setCreateBy(SecurityUtils.getUsername());
        return toAjax(productUnitService.updateById(productUnit));

    }


    @Operation(summary = "新增")
    @PostMapping
    public AjaxResult add(@RequestBody ProductUnit productUnit){
            if (!productUnitService.checkUnitNameUnique(productUnit)){

                //品牌名称被占用
                return error("新增商品'" + productUnit.getName() + "'失败，商品名称已存在");
            }
        productUnit.setCreateBy(SecurityUtils.getUsername());
            return toAjax(productUnitService.save(productUnit));
    }
}
